package com.xuecheng.content.services.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.XCPlusException;
import com.xuecheng.base.model.PageParam;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.services.mapper.CourseBaseMapper;
import com.xuecheng.content.services.mapper.CourseCategoryMapper;
import com.xuecheng.content.services.mapper.CourseMarketMapper;
import com.xuecheng.content.services.service.CourseBaseInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author:王亚栋
 * @Date: 2023/7/7 上午9:21
 * @Version:1.0
 */
@Service
@Slf4j(topic = "CourseBaseInfoServiceImpl")
public class CourseBaseInfoServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseInfoService {

    @Autowired
    private CourseBaseMapper courseBaseMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParam pageParam, QueryCourseParamDto queryCourseParamDto) {

        //拼装查询条件
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(!StringUtils.isEmpty(queryCourseParamDto.getCourseName()),CourseBase::getName,queryCourseParamDto.getCourseName());
        queryWrapper.eq(!StringUtils.isEmpty(queryCourseParamDto.getAuditStatus()),CourseBase::getAuditStatus,queryCourseParamDto.getAuditStatus());
        queryWrapper.eq(!StringUtils.isEmpty(queryCourseParamDto.getPublishStatus()),CourseBase::getStatus,queryCourseParamDto.getPublishStatus());

        //创建分页对象
        Page<CourseBase> page = new Page<>(pageParam.getPageNo(),pageParam.getPageSize());

        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);

        //数据列表
        List<CourseBase> items = pageResult.getRecords();

        log.info("items:{}",items);

        //总记录数
        long total = pageResult.getTotal();

        log.info("total:{}",total);

        PageResult<CourseBase> courseBasePageResult = new PageResult<>(items,
                total,
                pageParam.getPageNo(),
                pageParam.getPageSize());

        return courseBasePageResult;
    }

    /**
     * 新增课程功能
     * @param companyId 机构ID
     * @param addCourseDto
     * @return
     */
    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto) {

        //参数合法性校验
//        if (StringUtils.isEmpty(addCourseDto.getName())){
//
//            XCPlusException.cast("课程名称为空！");
//        }
//        if (StringUtils.isEmpty(addCourseDto.getMt())){
//
//            throw new RuntimeException("课程分类为空！");
//        }
//        if (StringUtils.isEmpty(addCourseDto.getSt())){
//
//            throw new RuntimeException("课程分类为空！");
//        }
//        if (StringUtils.isEmpty(addCourseDto.getGrade())){
//
//            throw new RuntimeException("课程等级为空！");
//        }
//        if (StringUtils.isEmpty(addCourseDto.getTeachmode())){
//
//            throw new RuntimeException("教育模式为空！");
//        }
//        if (StringUtils.isEmpty(addCourseDto.getUsers())){
//
//            throw new RuntimeException("适应人群为空！");
//        }
//        if (StringUtils.isEmpty(addCourseDto.getCharge())){
//
//            throw new RuntimeException("收费规则为空！");
//        }

        //向课程基本信息表course_base写入数据
        CourseBase courseBaseNew = new CourseBase();

        //从原始对象中Get拿到数据，向新对象中Set，比较繁琐复杂
//        courseBaseNew.setName(addCourseDto.getName());
//        courseBaseNew.setGrade(addCourseDto.getGrade());
//        courseBaseNew.setUsers(addCourseDto.getUsers());

        //只要属性名称一致，可以进行拷贝
        BeanUtils.copyProperties(addCourseDto,courseBaseNew);

        courseBaseNew.setCompanyId(companyId);
        courseBaseNew.setCreateDate(LocalDateTime.now());
        //审核状态 - 未提交
        courseBaseNew.setAuditStatus("202002");
        //发布状态 - 未发布
        courseBaseNew.setStatus("203001");
        //插入数据库
        int insert = courseBaseMapper.insert(courseBaseNew);

        if (insert <= 0){

            throw new RuntimeException("新增课程失败！");
        }


        //向课程营销表course_market写入数据
        CourseMarket courseMarketNew = new CourseMarket();

        BeanUtils.copyProperties(addCourseDto,courseMarketNew);

        //课程ID(主键)
        courseMarketNew.setId(courseBaseNew.getId());

        //保存课程营销信息
        saveCourseMarket(courseMarketNew);

        //从数据库查询课程的详细信息，包括两部分
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(courseBaseNew.getId());

        return courseBaseInfo;
    }



    /**
     * 查询课程信息
     * @param courseId
     * @return
     */
    @Override
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId){

        //1.从课程基本信息表查询
        CourseBase courseBase = courseBaseMapper.selectById(courseId);

        if (courseBase == null){

            return null;
        }
        //2.从课程营销表查询
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);

        if (courseMarket == null){

            return null;
        }
        //3.组装
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        //3.1拷贝
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        //通过courseCategoryMapper查询分类信息，将分类信息放在courseBaseInfoDto对象中
        //TODO 课程的分类名称设置到对象中

        return courseBaseInfoDto;
    }

    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto editCourseDto) {

        //拿到课程ID
        Long courseId = editCourseDto.getId();
        //查询课程信息(原始课程信息)
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        //数据合法性校验
        if (courseBase == null){

            XCPlusException.cast("课程不存在！");
        }

        if (!companyId.equals(courseBase.getCompanyId())){

            XCPlusException.cast("本机构不能修改其他机构的课程！");
        }

        //封装数据
        BeanUtils.copyProperties(editCourseDto,courseBase);

        //修改时间
        courseBase.setChangeDate(LocalDateTime.now());

        //更新数据库
        int updateResult = courseBaseMapper.updateById(courseBase);

        if (updateResult <= 0){

            XCPlusException.cast("修改课程失败！");
        }
        //查询课程信息
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(courseId);

        return courseBaseInfo;
    }


    /**
     * 单独写一个方法保存营销信息
     * TODO 存在则更新，不存在则添加
     * @param courseMarketNew
     */
    private void saveCourseMarket(CourseMarket courseMarketNew) {

        //参数的合法性校验
        //收费规则
        String charge = courseMarketNew.getCharge();
        if (StringUtils.isEmpty(charge)){

            throw new RuntimeException("收费规则为空！");
        }
        //如果收费，价格没有填写，也要抛异常
        if (charge.equals("201001")){

            if (courseMarketNew.getPrice() == null || courseMarketNew.getPrice().floatValue() <= 0){

                XCPlusException.cast("收费规则为空！");

            }
        }
        //从数据库查询营销信息，存在更新，不存在添加
        CourseMarket courseMarket = courseMarketMapper.selectById(courseMarketNew.getId());

        if (courseMarket == null){

            //插入数据库
            int insert = courseMarketMapper.insert(courseMarketNew);

            if(insert <= 0){

                throw new RuntimeException("新增课程营销失败！");
            }
        }else {

            //将courseMarketNew 拷贝到courseMarket
            BeanUtils.copyProperties(courseMarketNew,courseMarket);

            courseMarket.setId(courseMarketNew.getId());

            //更新数据
            int updateResult = courseMarketMapper.updateById(courseMarket);

            if (updateResult <= 0){

                throw new RuntimeException("更新课程营销失败！");
            }

        }
    }
}
